package  cn.edu.swu.lxy.auth;

import cn.edu.swu.lxy.db.BookResultSetVisitor;
import cn.edu.swu.lxy.db.DatabaseService;
import cn.edu.swu.lxy.entity.Book;
import cn.edu.swu.lxy.utils.HtmlHelper;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException{
        String user=request.getParameter("user");
        String pass=request.getParameter("pass");

        ServletContext context = request.getServletContext();
        DatabaseService service = (DatabaseService)context.getAttribute(DatabaseService.CONTEXT_KEY);
        try {
            List<User> users = service.query(
                    String.format("select * from user where name='%s' and passwd=md5('%s')",user,pass),
                    new UserResultSetVisitor()
            );

            if (users.size()>0){
                response.sendRedirect("./books");
            }else {
                response.sendRedirect("./login.html");
            }

        } catch (IOException | SQLException e) {
            throw new ServletException(e);
        }
    }
    }
